export default class Dep {
  constructor() {
    //实例化一个weekmap数据结构的弱引用数据
    this.effectMap = new WeakMap();
  }

  //静态属性是保存当前watch方法或者是watchEffect方法的回调函数
  static effectCB = null;

  //收集依赖
  collect(target, key) {
    // console.log(target, key);
    //{a: 1, b: {…}}a: 1b: {c: 2}     'a'
    const { effectCB } = Dep;
    //回调函数存在时才去收集
    if (effectCB) {
      let depMap = this.effectMap.get(target);
      //没有时创建一个Map数据
      if (!depMap) {
        depMap = new Map();
        //将创建的Map数据保存至对于WeakMap的属性里
        this.effectMap.set(target, depMap);
        // console.log(this.effectMap);
        //WeakMap{ {Object => Map({key: {c: 2}, value: Map: {...}})}, {Object => Map(0)}, ... }
      }

      //从Map数据中获取对应属性名的依赖
      let deps = depMap.get(key);

      if (!deps) {
        deps = new Set();
        depMap.set(key, deps);
      }

      //新值依赖项
      deps.add(effectCB);
    }
  }

  //通知
  notify(target, key, value, oldValue) {
    const depMap = this.effectMap.get(target);
    // console.log(depMap);
    //Map(2) {'a' => Set(2) {ƒ, ƒ}, 'b' => Set(2)}
    if (!depMap) return;

    const deps = depMap.get(key);
    // console.log(deps);
    //Set(2) {ƒ, ƒ}

    //遍历所有回调函数并执行
    deps.forEach((dep) => {
      const newValue = dep(value, oldValue);
      //computed中xxx.value的值
      if (dep.computedRef) {
        dep.computedRef.value = newValue;
      }
    });
  }
}
